<?php

/*
*/

class Cost_type_model extends CI_Model
{

	static $table;

	function __construct()
	{
		parent::__construct();
		//载入库文件
		$this->load->library('test_database');
		$this->test_database->test();
		//载入核心类
		$this->load->database($this->test_database->get_db());
		//载入库文件
		$this->load->library('form_validation');
		//载入本地语言文件
		$this->lang->load('form_validation','chinese');
		//初始化
		$this->table = 'cost_types';
	}

	//创建一个货品类型
	public function create()
	{
		$this->form_validation->set_rules('name', '类别', 'trim|required|min_length[2]|max_length[18]|unique[Cost_type_model]|xss_clean');
		if ( $this->form_validation->run() )
		{
			$v['name'] = $this->input->post('name');
			$v['create_date'] = time();
			$this->db->insert($this->table, $v);
			if (1 == $this->db->affected_rows())
			{
				return $this->db->insert_id();
			}
		}
		return false;
	}

	//更新一个货品类目
	public function update()
	{
		$this->form_validation->set_rules('name', '类目', 'trim|required|min_length[2]|max_length[18]|unique[Cost_type_model]|xss_clean');
		if ( $this->form_validation->run() )
		{
			$id = $this->input->post('id');
			$v['name'] = $this->input->post('name');
			//判断存在修改此用户
			if ($user = $this->getOne($id))
			{
				if ($user['name'] != $v['name'])
				{
					$this->db->where('id', $id);
					$this->db->update($this->table, $v);
					return true;
				}
			}
		}
		return false;
	}

	//获取一个类目信息，不存在返回false;
	public function getOne($id)
	{
		$query = $this->db->get_where($this->table, array('id' => $id));
		if (1 == $query->num_rows())
		{
			foreach ($query->result() as $v)
			{
				return get_object_vars($v);
			}
		}
		return false;
	}

	//获取所有类目
	public function _list($df)
	{
		if ('enable' == $df)
		{
			$df = 0;
		}
		else
		{
			$df = 1;
		}
		$this->db->order_by("del_flg ASC");
		$this->db->where('del_flg', $df);
		$query = $this->db->get($this->table);
		return $query->result();
	}

	//禁用一个类型
	public function del($id)
	{
		if ($this->getOne($id))
		{
			$v['del_flg'] = '1';
			$this->db->where('id', $id);
			$this->db->update($this->table, $v);
			return true;
		}
		return false;
	}

	//回收一个类型
	public function recover($id)
	{
		if ($this->getOne($id))
		{
			$v['del_flg'] = '0';
			$this->db->where('id', $id);
			$this->db->update($this->table, $v);
			return true;
		}
		return false;
	}

	//验证类型的唯一性，MY_Form_validation 扩展类使用
	public function unique($name)
	{
		$query = $this->db->get_where($this->table, array('name'=>$name), 1);
		if (1 == $query->num_rows()) {
			return false;
		}
		return true;
	}

}